/**
 * https://leetcode-cn.com/problems/trapping-rain-water/
 * @param {number[]} height
 * @return {number}
 */
 var trap = function(height) {
  const stack = [];
  let sum = 0;
  for (let i = 0; i < height.length; i++) {
      let current = height[i];
      let pushIndex = stack.length;
      // 出栈，累加雨水
      if (stack.length && current >= stack[stack.length - 1][0]) {
          let bottom = stack[stack.length - 1][0];
          pushIndex--;
          while (pushIndex > 0) {
              const [height, index] = stack[pushIndex - 1];
              sum+= ((Math.min(height, current) - bottom) * (i - index - 1));
              bottom = Math.min(height, current);
              if (current < height) {
                  break;
              }
              pushIndex--;
          }
      }
      // 入栈
      stack.splice(pushIndex, stack.length, [current, i]);
  }
  return sum
};
